package org.example.webserver.controller;

import com.alibaba.fastjson.JSONArray;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.webserver.pojo.Commodity;
import org.example.webserver.pojo.Order;
import org.example.webserver.pojo.OrderState;
import org.example.webserver.pojo.User;
import org.example.webserver.service.CommodityService;
import org.example.webserver.service.OrderService;
import org.example.webserver.service.UserService;
import org.example.webserver.utils.Result;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/welcome")
public class WelcomeController {
    @Resource
    UserService userService;
    @Resource
    CommodityService commodityService;
    @Resource
    OrderService orderService;

    @PostMapping("/showAll")
    public Result<List<Commodity>> showCommodity(){
        List<Commodity> commodityList=commodityService.showAllCommodity();
        return Result.success(commodityList);
    }

    @PostMapping("/showOrder")
    public Result<JSONArray> showOrder(HttpServletRequest request){
        JSONArray jsonArray=orderService.findOrderByUser(((User)request.getSession().getAttribute("user")).getId());
        return Result.success(jsonArray);
    }

    @PostMapping("/buy")
    public Result<Order> buy(@RequestBody Order order){
        orderService.buy(order);
        return Result.success();
    }

    @PostMapping("cancel")
    public Result<OrderState> cancel(@RequestParam int id,HttpServletRequest request){
        OrderState orderState=orderService.cancel(id);
        if(orderState!=null){
            return Result.success(orderState);
        }else{
            return Result.error("006","订单状态不匹配");
        }
    }
}
